package yunjiao.javatutorials.guava.base;

import com.google.common.base.Equivalence;

import java.util.Objects;

/**
 * 对象字段比较
 *
 * @author yangyunjiao
 */
public class PersonNameEquivalence extends Equivalence<PersonNameEquivalence.Person> {
    @Override
    protected boolean doEquivalent(Person a, Person b) {
        if (a == null && b == null) return true;
        if (a == null || b == null) return false;
        return Objects.equals(a.name(), b.name());
    }

    @Override
    protected int doHash(Person person) {
        return person == null ? 0 : Objects.hashCode(person.name());
    }

    public record Person(
        String name,
        int age
    ){}

    public static void main(String[] args) {
        Person p1 = new Person("张三", 25);
        Person p2 = new Person("李四", 25);
        Person p3 = new Person("张三", 80);

        PersonNameEquivalence personNameEquivalence = new PersonNameEquivalence();
        System.out.println(personNameEquivalence.equivalent(p1, p2));
        System.out.println(personNameEquivalence.equivalent(p1, p3));
    }
}
